package com.chenyue.cm.pay.wx;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @author libingxing
 */
@Component
@EnableConfigurationProperties(UploadProperties.class)
public class WxConfig extends WxPayConfig {

    private byte[] certData;

    private static TempDomain tempDomain = new TempDomain();

    private final UploadProperties uploadProperties;

    public WxConfig(UploadProperties uploadProperties) {
        this.uploadProperties = uploadProperties;
    }

    public void init() throws Exception {
        //证书位置
        String certPath = uploadProperties.getCertDir();
        File file = new File(certPath);
        if (!file.exists()) {
            return;
        }
        InputStream certStream = new FileInputStream(file);
        this.certData = new byte[(int) file.length()];
        certStream.read(this.certData);
        certStream.close();
    }

    /**
     * 微信开放平台审核通过的应用AppId
     * （请登录open.weixin.qq.com查看，注意与公众号的AppId不同）
     *
     * @return AppId
     */
    @Override
    public String getAppId() {
        return "wx6f3f7dcb8935076c";
    }

    /**
     * 微信支付分配的商户号1515346721
     *
     * @return 商户号
     */
    @Override
    public String getMchId() {
        return "1613245628";
    }

    /**
     * appSecret微信签名密钥
     *
     * @return appSecret bb27c92b4dbcfbf02463761d086946ef
     */
    @Override
    public String getKey() {
        return "db5ed98adfa146e891e3b0e1cc1bde94";
    }

    @Override
    public InputStream getCertStream() {
        return new ByteArrayInputStream(this.certData);
    }

    @Override
    public int getHttpConnectTimeoutMs() {
        return 8000;
    }

    @Override
    public int getHttpReadTimeoutMs() {
        return 10000;
    }

    @Override
    public IWXPayDomain getWXPayDomain() {
        if (tempDomain == null) {
            tempDomain = new TempDomain();
        }
        return tempDomain;
    }

    static class TempDomain implements IWXPayDomain {

        @Override
        public void report(String domain, long elapsedTimeMillis, Exception ex) {

        }

        @Override
        public DomainInfo getDomain(WxPayConfig config) {
            return new DomainInfo("api.mch.weixin.qq.com", true);
        }

    }

}
